
package com.study.module.ratelimit;


import com.study.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 限流切面类
 */
@Aspect
@Component
@Slf4j
public class RateLimitAspect {

    @Resource
    private RateLimitService rateLimitService;

    @Pointcut("@annotation(com.study.module.ratelimit.RateLimit)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //获取被拦截的方法
        Method method = ((MethodSignature) point.getSignature()).getMethod();

        RateLimit rateLimit = AnnotationUtils.findAnnotation(method, RateLimit.class);

        if (Objects.nonNull(rateLimit)) {
            RRateLimiter rateLimiter = rateLimitService.getRateLimiter(rateLimit.name());

            //如果令牌桶不存在就初始化一个令牌桶
            if (!rateLimiter.isExists()) {
                rateLimiter.trySetRate(RateType.OVERALL, rateLimit.count(), rateLimit.timeUnit().toSeconds(rateLimit.period()), RateIntervalUnit.SECONDS);
            }

            //尝试获取令牌...
            if (!rateLimiter.tryAcquire()) {
                return R.fail("系统繁忙");
            }
        }

        return point.proceed();
    }

}